package com.example.demo.controller;

import com.example.demo.domain.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public String IndexPages(){
        return "pages/user/index.html";
    }


    @GetMapping("/login")
    public String LoginPage(){
        return "pages/user/login.html";
    }

    @PostMapping("/login")
    public String Login(User user,HttpServletRequest request ){
        //根据用户ID从数据库获得该ID的密码，然后判断
        int res = userService.checkUser(user);
        if( res == 2)//成功
        {
            //session
            HttpSession session=request.getSession();
            session.setAttribute("userID",user.getUserId());
            return "redirect:/hotel/search";
        }
        else if(res == 1)//用户不存在
        {
            return "/pages/user/loginfailed.html";
        }else{//登录失败
            return "/pages/user/loginfailed.html";
        }
    }

    @GetMapping("/register")
    public String loginPages() {
        return "pages/user/registration.html";
    }

    @PostMapping("/register")
    public String Register(User user, @RequestParam("password2") String password2)
    {
        int check = userService.checkUser(user);
        if(check==1){ //用户名不存在
            if(user.getPassword().equals(password2)){
                user.setUserId(null);
                userService.saveUser(user);
                return "pages/user/registersuccess.html";
            }else{
                return "pages/user/registerfailed2.html";
            }
        }
        else{
            return "pages/user/registerfailed.html";
        }
    }

}